#include "d_Math.h"
#include <GL/gl.h>
#include <iostream>
using namespace std;

using namespace d_Math;

d_Plane::d_Plane(d_Vec3f origin, d_Vec3f normal) {
  this->normal = norm(normal);
  this->origin = origin;
  equation[0] = normal[0];
  equation[1] = normal[1];
  equation[2] = normal[2];
  equation[3] = -(normal[0]*origin[0]+normal[1]*origin[1]
                 +normal[2]*origin[2]);
}

d_Plane::d_Plane(d_Vec3f p1,d_Vec3f p2, d_Vec3f p3)
{
  normal = cross((p2-p1),(p3-p1));
  normal = norm(normal);
  origin = p1;
  equation[0]  = normal[0];
  equation[1]  = normal[1];
  equation[2]  = normal[2];
  equation[3]  = -(normal[0]*origin[0]+normal[1]*origin[1]
                 +normal[2]*origin[2]);
}
bool d_Plane::isFrontFacingTo(d_Vec3f direction)
{
  double d = dot(normal,direction);
  return (d <= 0);
}

double d_Plane::signedDistanceTo(d_Vec3f point)
{
  return dot(point,normal) + equation[3];
}

void d_Plane::drawCircle(float r)
{
	d_Vec3f y = normal;
	d_Vec3f x = norm(cross(normal, d_Vec3f(normal[0], 3*normal[1]+0.1, -5*normal[2]+0.1)));
	d_Vec3f z = cross(x,normal);
	d_Vec3f t = x*r;
	d_Mat4f tr;
	glPushMatrix();
	glTranslatef(origin[0], origin[1], origin[2]);
	glBegin(GL_LINE_LOOP);
		//glColor3f(1,0,0);
		//glVertex3fv(y.p);
		//glColor3f(0,1,0);
		//glVertex3f(0,0,0);
		glColor3f(0,0,1);
		for(float theta = 0; theta < 6.4; theta += 0.4)
		{
			tr.make_hrot(normal,theta);
			//d_Vec3f tv3 = t.rotateByY(theta);
			d_Vec4f tv = tr*d_Vec4f(t[0], t[1], t[2],1);
			glVertex3f(tv[0],tv[1],tv[2]);
		}	
	glEnd();
	glPopMatrix();
}







